import Film from "@/components/film";
import { getFilmList } from "@/services/film";
import { InfiniteScroll, Tabs } from "antd-mobile";
import { useEffect, useMemo, useState } from "react";
import { useRequest } from "umi";

const FilmsPage = () => {
  // 当前电影类型 1-正在热映 2-即将上映
  const [type, setType] = useState("1");
  // 页码
  const [page, setPage] = useState(1);
  // 页码大小
  const [pageSize, setPageSize] = useState(10);
  // 用于页面显示的数据
  const [list, setList] = useState<IFilm[]>([]);

  const { data, loading } = useRequest(
    () => getFilmList(type, page, pageSize),
    {
      // 依赖
      refreshDeps: [type, page, pageSize],
    }
  );

  useEffect(() => {
    console.log("datadata");
    const films = (data as any)?.films;
    if (films) {
      console.log("films", films);
      setList((list) => [...list, ...films]);
    }
  }, [data]);

  // 总的页数
  const pageTotal = useMemo(() => {
    const total = data ? (data as any).total : 1;
    return Math.ceil(total / pageSize);
  }, [data, pageSize]);

  // 是否还有更多
  const hasMore = useMemo(() => {
    return page < pageTotal;
  }, [page, pageTotal]);

  /**
   * Tabs 切换
   */
  const handleTabChange = (key: string) => {
    // 如何重新调用接口, 修改 type 。然后 type 作为 useRequest 的依赖项
    setPage(1);
    setType(key);
    setList([]);
  };

  /**
   * 加载更多的逻辑
   */
  const loadMore = () => {
    // 修改 page , 让接口重新调用
    console.log("loadMore", loading);
    setPage((page) => page + 1);
    return Promise.resolve();
  };

  return (
    <div className="films-page">
      <Tabs onChange={handleTabChange}>
        <Tabs.Tab title="正在热映" key="1" />
        <Tabs.Tab title="即将上映" key="2" />
      </Tabs>

      {list.map((item) => {
        return <Film key={item.filmId} {...item} />;
      })}

      {!loading && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />}
    </div>
  );
};

export default FilmsPage;
